package cn.mandy.sysadmin.controller;

import cn.mandy.sysadmin.common.api.CommonResult;
import cn.mandy.sysadmin.common.util.MandyTree;
import cn.mandy.sysadmin.dto.*;
import cn.mandy.sysadmin.model.*;
import cn.mandy.sysadmin.service.MonitorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Description :
 *
 * @author <a href= "mailto:342987890@qq.com">Winter</a>
 * create date: 2020/4/13 0013
 * project: sysadmin
 * @since
 */
@Controller
@Api(tags = "MandySysadminController", description = "监控调度")
@RequestMapping("/monitor")
public class MonitorController {
    @Autowired
    MonitorService monitorService;

    @ApiOperation("参数列表")
    @RequestMapping(value = "/global-list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MonitorGlobal>> globalList() {
        List<MonitorGlobal> cfgGlobals = monitorService.globalList();
        return  CommonResult.success(cfgGlobals);
    }

    @ApiOperation("参数列表参数更新")
    @RequestMapping(value = "/global-update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> globalUpdate(@RequestBody MonitorGlobal newCfgGlobal) {
        Integer ret = monitorService.globalUpdate(newCfgGlobal);
        if (ret.equals(0)) {
            return CommonResult.success("更新参数成功");
        }

        return CommonResult.failed("更新参数失败!");
    }

    @ApiOperation("主机参数更新")
    @RequestMapping(value = "/host-update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> hostUpdate(@RequestBody MonitorHost host) {
        Integer ret = monitorService.monitorHostUpdate(host);
        if (ret.equals(0)) {
            return CommonResult.success("更新参数成功");
        }

        return CommonResult.failed("更新参数失败!");
    }

    @ApiOperation("主机复制")
    @RequestMapping(value = "/host-copy", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorHost> hostCopy(@RequestBody MonitorHost host) {
        MonitorHost newHost = monitorService.cfgHostCopy(host);
        if (newHost != null) {
            return CommonResult.success(newHost);
        }

        return CommonResult.failed("操作失败!");
    }

    @ApiOperation("主机列表")
    @RequestMapping(value = "/host-list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MonitorHost>> hostList() {
        List<MonitorHost> hosts = monitorService.monitorHostList();
        return  CommonResult.success(hosts);
    }

    @ApiOperation("作业更新")
    @RequestMapping(value = "/job-update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorJob> jobUpdate(@RequestBody MonitorJob monitorJob) {
        MonitorJob newJobGroup = monitorService.monitorJobUpdate(monitorJob);
        if (newJobGroup != null) {
            return CommonResult.success(newJobGroup);
        }
        return CommonResult.failed();
    }


    @ApiOperation("作业删除")
    @RequestMapping(value = "/job-delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> jobDelete(@RequestBody List<MyId> param) {
        int ret = monitorService.jobDelete(param);
        if (ret == 0) {
            return CommonResult.success("删除成功！");
        }
        return CommonResult.failed("删除失败！");
    }


    @ApiOperation("作业列表")
    @RequestMapping(value = "/job-list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MonitorJob>> jobList() {
        List<MonitorJob> jobs = monitorService.monitorJobList();
        return  CommonResult.success(MandyTree.listToTree(jobs));
    }

    @ApiOperation("作业复制(包括进程组复制)")
    @RequestMapping(value = "/job-copy", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorJob> jobCopy(@RequestBody MonitorJob oldJob) {
        MonitorJob newJob = monitorService.monitorJobGroupCopy(oldJob);
        if (newJob != null) {
            return CommonResult.success(newJob);
        }

        return CommonResult.failed("操作失败!");
    }

    @ApiOperation("作业重排序")
    @RequestMapping(value = "/job-resort", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> jobResort(@RequestBody List<MyId> param) {
        monitorService.monitorJobResort(param);
        return  CommonResult.success("作业组重排序成功！");
    }

    /**
     * 包括作业组上线
     * @param param
     * @return
     */
    @ApiOperation("作业上线")
    @RequestMapping(value = "/job-enable", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> jobEnable(@RequestBody List<MyId> param) {
        monitorService.jobEnable(param);
        return  CommonResult.success("作业上线成功！");
    }

    /**
     * 包括作业组下线
     * @param param
     * @return
     */
    @ApiOperation("作业下线")
    @RequestMapping(value = "/job-disable", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> jobDisable(@RequestBody List<MyId> param) {
        monitorService.jobDisable(param);
        return  CommonResult.success("作业下线成功！");
    }

    @ApiOperation("新增作业计划")
    @RequestMapping(value = "/plan-create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorPlan> planCreate(@RequestBody MonitorPlan cfgJobCrontab) {
        MonitorPlan newPlan = monitorService.planCreate(cfgJobCrontab);
        return  CommonResult.success(newPlan);
    }

    @ApiOperation("删除作业计划")
    @RequestMapping(value = "/plan-delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> planDelete(@RequestBody List<MyId> myIds) {
        monitorService.planDelete(myIds);
        return  CommonResult.success("删除成功");
    }

    @ApiOperation("启用计划")
    @RequestMapping(value = "/plan-enable", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> crontabEnable(@RequestBody List<MyId> myIds) {
        monitorService.planEnable(myIds);
        return  CommonResult.success("启用成功");
    }

    @ApiOperation("撤消计划")
    @RequestMapping(value = "/plan-disable", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> planDisable(@RequestBody List<MyId> myIds) {
        monitorService.planDisable(myIds);
        return  CommonResult.success("撤消成功");
    }


    @ApiOperation("更新依赖")
    @RequestMapping(value = "/dependence-update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<MonitorDependence>> dependenceUpdate(@RequestBody List<MonitorDependence> dependencies) {
        return  CommonResult.success(monitorService.dependenceUpdate(dependencies));
    }

    @ApiOperation("删除依赖")
    @RequestMapping(value = "/dependence-delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> dependenceDelete(@RequestBody List<MyId> myIds) {
        monitorService.dependenceDelete(myIds);
        return  CommonResult.success("删除成功");
    }
    ///dependence/delete

    @ApiOperation("获取任务记录")
    @RequestMapping(value = "/task-list", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<MonitorTask>> taskList(@RequestBody TaskListParam param) {
        List<MonitorTask> tasks;
        if ("current".equals(param.getOperatorType())) {
            tasks =  monitorService.listCurrentTask(param.getJobId(), param.getRecordCount());
        }else if ("before".equals(param.getOperatorType())){
            tasks =  monitorService.listTaskBefore(param.getJobId(), param.getScheduleTime(), param.getRecordCount());
        }else {
            tasks =  monitorService.listTaskAfter(param.getJobId(), param.getScheduleTime(), param.getRecordCount());
        }

        return CommonResult.success(tasks);
    }

    //listChildrenCurrentTask
    @ApiOperation("获取子作业的任务记录")
    @RequestMapping(value = "/children-task-list", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<MonitorTask>> listChildrenTask(@RequestBody TaskListParam param) {
        List<MonitorTask> tasks = new ArrayList<>();
        if ("current".equals(param.getOperatorType())) {
            tasks =  monitorService.listChildrenCurrentTask(param.getJobId(), param.getRecordCount());
        }else if ("before".equals(param.getOperatorType())){
            tasks =  monitorService.listAllChildrenTaskBefore(param.getJobId(), param.getScheduleTime(), param.getRecordCount());
        }else {
            tasks =  monitorService.listAllChildrenTaskAfter(param.getJobId(), param.getScheduleTime(), param.getRecordCount());
        }

        if (tasks != null){
            return CommonResult.success(MandyTree.listToTree(tasks));
        }

        return CommonResult.success(null);
    }

    @ApiOperation("读取任务运行日志")
    @RequestMapping(value = "/task-log", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> taskLogReader(@RequestBody MonitorLogFileParam param) {
        String retString = null;
        try {
            retString = monitorService.getTaskLogfile(param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return CommonResult.success(retString);
    }

    @ApiOperation("撤销任务")
    @RequestMapping(value = "/task-cancel", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorTask> taskCancel(@RequestBody MonitorTaskCancelParam param) {
        int ret = monitorService.taskCancel(param.getId(), param.getOldStatus(), param.getDestStatus(), param.getCancelReason());
        if (ret == 0){
            MonitorTask task = monitorService.selectTaskById(param.getId());
            return CommonResult.success(task);
        }

        return CommonResult.failed("任务状态已经发生改变, 请刷新一下");
    }

    @ApiOperation("创建任务")
    @RequestMapping(value = "/task-create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorTask> taskCreate(@RequestBody MyId param) {
        MonitorTask task = monitorService.taskCreateNow(param.getId());
        if (task != null){
            task = monitorService.selectTaskById(task.getId());
            return CommonResult.success(task);
        }

        return CommonResult.failed("创建任务失败");
    }

    @ApiOperation("任务重做")
    @RequestMapping(value = "/task-redo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorTask> taskRedo(@RequestBody MyId param) {
        MonitorTask task = monitorService.taskRedoNow(param.getId());
        if (task != null){
            task = monitorService.selectTaskById(task.getId());
            return CommonResult.success(task);
        }

        return CommonResult.failed("创建重做任务失败");
    }


    @ApiOperation("获取作业的当前任务")
    @RequestMapping(value = "/task-current", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<MonitorTask> taskProcessList(@RequestBody MyId param) {
        MonitorTask currentTask = monitorService.getCurrentTask(param.getId());
        return CommonResult.success(currentTask);
    }


    @ApiOperation("查询作业组的当前任务")
    @RequestMapping(value = "/task-current-group", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<MonitorTask>> taskCurrentGroup(@RequestBody MyId jobGroupId) {
        List<MonitorTask> tasks = monitorService.currentTaskListByJobGroupId(jobGroupId.getId());
        List<MonitorTask> taskTree = MandyTree.listToTree(tasks);
        return  CommonResult.success(taskTree);
    }

    @ApiOperation("停止任务组下各任务")
    @RequestMapping(value = "/task-group-stop", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> taskGroupStop(@RequestBody MonitorTaskGroupStopParam taskGroupStopParam) {
        int ret = monitorService.taskGroupStop(taskGroupStopParam.getJobId(), taskGroupStopParam.getTaskId(), taskGroupStopParam.getStatus());
        if (ret == 0){
            return CommonResult.success("提交成功");
        }
        return CommonResult.failed("提交失败, 当前进程不在运行状态");
    }

    /***
     * 正常情况下, 一个作业只会有当前任务及当前任务往后的任务可能会有变化。
     * 当前任务是因为正在运行，所以各个子任务会有变化。
     * 当前任务往后的，是因为计划变更或者前面任务完成了，又到达后面任务的运行时间。
     */
    @ApiOperation("刷新作业组任务")
    @RequestMapping(value = "/task-refresh", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<MonitorTask>> taskRefresh(@RequestBody TaskRefreshParam taskRefreshParam) {
        List<MonitorTask> tasks = monitorService.taskRefresh(taskRefreshParam);
        //List<MonitorTask> taskTree = MandyTree.listToTree(tasks);
        return  CommonResult.success(tasks);
    }

}
